import { Node, _decorator, Component, Vec3 } from 'cc';
import RowFallClear_CellFunctions from '../Core/RowFallClear_CellFunctions';

const { ccclass, property } = _decorator;

@ccclass('RowFallClear_TouchManager')
export default class RowFallClear_TouchManager extends Component {
    public static Instance: RowFallClear_TouchManager;
    startPos: Vec3;
    currentPos: Vec3;
    endPos: Vec3;
    force: number;
    hasMove: boolean = false;
    isPress: boolean = false;
    horizontalTouchDistance = 40;
    verticalTouchDistance = 100;
    onLoad() {
        RowFallClear_TouchManager.Instance = this;
    }
    start() {
        this.registerEvent();
    }
    registerEvent() {
        this.node.on(Node.EventType.TOUCH_START, this.onEventStart, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onEventMove, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onEventCancel, this);
        this.node.on(Node.EventType.TOUCH_END, this.onEventEnd, this);
    }
    Move(x: number) {
        this.hasMove = true;
        if (x < 0) {
            RowFallClear_CellFunctions.MoveLefOrRight(-1);
        }
        else if (x > 0) {
            RowFallClear_CellFunctions.MoveLefOrRight(+1);
        }
    }
    onEventStart(event) {
        this.startPos = event.getLocation();
        this.currentPos = event.getLocation();
        this.isPress = true;
        this.force = -0.4;
    }
    onEventMove(event) {
        this.currentPos = event.getLocation();
        let diffX: number = this.currentPos.x - this.startPos.x;
        if (Math.abs(diffX) > this.horizontalTouchDistance) {
            if (this.hasMove == false) {
                this.Move(diffX);
            }
        }
    }
    update(dt) {
        if (this.isPress == true) {
            let diffX: number = this.currentPos.x - this.startPos.x;
            if (Math.abs(diffX) > this.horizontalTouchDistance) {
                this.force += dt;
                if (this.force >= 0.1) {
                    this.force = 0;
                    this.Move(diffX);
                }
            }
        }
    }
    onEventCancel(event) {
        this.endPos = event.getLocation();

        let diffY: number = this.endPos.y - this.startPos.y;
        if (this.hasMove == false) {
            if (diffY < -this.verticalTouchDistance) {
                RowFallClear_CellFunctions.ControlMoveDown();
            }
        }

        this.hasMove = false;
        this.isPress = false;
    }
    onEventEnd(event) {
        this.endPos = event.getLocation();

        let diffY: number = this.endPos.y - this.startPos.y;
        if (this.hasMove == false) {
            if (diffY < -this.verticalTouchDistance) {
                RowFallClear_CellFunctions.ControlMoveDown();
            }
        }

        this.hasMove = false;
        this.isPress = false;
    }
}